package com.suntront.module_bluetooth.bluetoothlist

import android.Manifest
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.content.IntentFilter
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.mtjsoft.www.kotlinmvputils.base.BaseRecycleViewModel
import com.mtjsoft.www.kotlinmvputils.base.BaseRecycleviewActivity
import com.mtjsoft.www.kotlinmvputils.constants.RouterConstants
import com.mtjsoft.www.kotlinmvputils.emen.EventEnum
import com.mtjsoft.www.kotlinmvputils.imp.PermissionsResultListener
import com.mtjsoft.www.kotlinmvputils.model.EventMessage
import com.mtjsoft.www.kotlinmvputils.utils.KLog
import com.suntront.module_bluetooth.BlueToothTool
import com.suntront.module_bluetooth.adapter.BlueToothAdapter
import com.suntront.module_bluetooth.broadcastreceiver.FindBlueToothReceiver
import com.suntront.module_bluetooth.model.BlueToothModel
import com.tencent.mmkv.MMKV


/**
 * @author mtj
 * @Package com.mtjsoft.mvvmtest.bluetoothlist
 * @date 2020-05-21 13:28:46
 */
@Route(path = RouterConstants.BlueTooth_List)
class BlueToothRecycleViewActivity : BaseRecycleviewActivity<BlueToothModel, BlueToothViewModel>() {


    private val REQUEST_ENABLE_BT = 100

    private val permissions: ArrayList<String> = object : ArrayList<String>() {
        init {
            add(Manifest.permission.BLUETOOTH)
            add(Manifest.permission.BLUETOOTH_ADMIN)
            add(Manifest.permission.ACCESS_FINE_LOCATION)
            add(Manifest.permission.ACCESS_COARSE_LOCATION)
        }
    }

    private val mFindBlueToothReceiver = FindBlueToothReceiver()

    override fun providerVMClass(): Class<BlueToothViewModel>? {
        return BlueToothViewModel::class.java
    }

    override fun loadActivityInfo() {
        setPageTitle("蓝牙配对")
        // 禁用下拉刷新和上拉加载
        viewModel.refresh.value = false
        viewModel.load_more.value = false
        setIsRegisteredEventBus(true)
        // 申请权限，开启蓝牙
        requestPermission(permissions, true, object : PermissionsResultListener {
            override fun onPermissionGranted() {
                if (BlueToothTool.instance.getBluetoothIsCanUse() && !BlueToothTool.instance.getBluetoothIsOpen()) {
                    val enableIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                    startActivityForResult(enableIntent, REQUEST_ENABLE_BT)
                }
            }

            override fun onPermissionDenied() {
            }
        })
        //
        registerReceiver(mFindBlueToothReceiver, BlueToothTool.instance.getBlueToothIntentFilter())
    }

    override fun setItemDecoration(): Int {
        return 0
    }

    override fun setPageSize(): Int {
        return Int.MAX_VALUE
    }

    override fun setLayoutManagerType(): BaseRecycleViewModel.LayoutManager {
        return BaseRecycleViewModel.LayoutManager.LinearLayoutManager
    }

    override fun setCount(): Int {
        return 2
    }

    override fun instanceAdapter(list: MutableList<BlueToothModel>): BaseQuickAdapter<BlueToothModel, BaseViewHolder> {
        return BlueToothAdapter(getContext(), list, this)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                REQUEST_ENABLE_BT -> {
                    // 开启蓝牙，刷新数据
                    onRefresh()
                }
            }
        }
    }

    override fun onReceiveEvent(event: EventMessage) {
        super.onReceiveEvent(event)
        when (event.getCode()) {
            EventEnum.BluetoothDevice_ACTION_STARTED.code -> {
                // 扫描开始
                showLoadingUI("正在扫描...", false)
            }
            EventEnum.BluetoothDevice_ACTION_FINISHED.code -> {
                hideLoadingUI()
            }
            EventEnum.BluetoothDevice_ACTION_FOUND.code -> {
                val model: BlueToothModel = event.getData() as BlueToothModel
                if (!viewModel.list.value!!.contains(model)) {
                    viewModel.list.value!!.add(model)
                    getRecyclerView().adapter?.notifyItemInserted(getRecyclerView().adapter?.itemCount!!)
                    getRecyclerView().smoothScrollToPosition(viewModel.list.value!!.size - 1)
                }
            }
        }
    }

    override fun onItemClick(position: Int, view: View) {
        super.onItemClick(position, view)
        val model = viewModel.list.value!![position]
        when (model.bondState) {
            BluetoothDevice.BOND_BONDED -> {
                toast("该设备已配对")
            }
            BluetoothDevice.BOND_BONDING -> {
                toast("该设备正在配对中")
            }
            BluetoothDevice.BOND_NONE -> {
                val device = mFindBlueToothReceiver.deviceMap[model.name + "_" + model.address]
                if (device != null) {
                    BlueToothTool.instance.createBond(device)
                    MMKV.defaultMMKV().encode("bluetooth_address", model.address)
                    toast("配对成功")
                }
            }
        }
    }

    override fun onDestroy() {
        hideLoadingUI()
        BlueToothTool.instance.cancelDiscovery()
        unregisterReceiver(mFindBlueToothReceiver)
        super.onDestroy()
    }
}